<template>
  <a-modal
    :visible="visible"
    title="添加美容服务项目"
    width="800px"
    :footer="null"
    @cancel="handleCancel"
  >
    <div class="service-modal">
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-input-search
              v-model:value="searchKeyword"
              placeholder="搜索服务项目"
              @search="searchServices"
              style="width: 100%"
            />
          </a-col>
          <a-col :span="12">
            <a-select
              v-model:value="selectedCategory"
              placeholder="选择类别"
              style="width: 100%"
              @change="filterServices"
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="洗澡">洗澡</a-select-option>
              <a-select-option value="美容">美容</a-select-option>
              <a-select-option value="护理">护理</a-select-option>
              <a-select-option value="造型">造型</a-select-option>
            </a-select>
          </a-col>
        </a-row>
      </div>

      <!-- 服务项目列表 -->
      <div class="services-list">
        <a-table
          :columns="columns"
          :data-source="filteredServices"
          :pagination="false"
          size="small"
          :row-selection="rowSelection"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'price'">
              ¥{{ record.price.toFixed(2) }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button
                type="primary"
                size="small"
                @click="selectService(record)"
              >
                选择
              </a-button>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 已选择的服务项目 - 固定在底部 -->
      <div v-if="selectedServices.length > 0" class="selected-services">
        <div class="selected-header">
          <h4>已选择的服务项目 ({{ selectedServices.length }})</h4>
          <a-button type="text" size="small" @click="clearAllSelected">
            清空全部
          </a-button>
        </div>
        <div class="selected-list">
          <div
            v-for="service in selectedServices"
            :key="service.id"
            class="selected-item"
          >
            <div class="service-info">
              <span class="service-name">{{ service.name }}</span>
              <span class="service-category">{{ service.category }}</span>
            </div>
            <div class="service-price">
              <span class="price">¥{{ service.price.toFixed(2) }}</span>
              <a-input-number
                v-model:value="service.quantity"
                :min="1"
                :max="10"
                size="small"
                style="width: 80px; margin-left: 8px"
              />
            </div>
            <a-button
              type="text"
              size="small"
              danger
              @click="removeService(service)"
            >
              🗑️
            </a-button>
          </div>
        </div>

        <div class="total-section">
          <span class="total-label">总计：</span>
          <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button
          type="primary"
          @click="handleOk"
          :disabled="selectedServices.length === 0"
        >
          确认添加
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible',visible: boolean): void;
  (e: 'success',data: any): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const searchKeyword = ref('');
const selectedCategory = ref('');
const selectedServices = ref<any[]>([]);

// 模拟服务项目数据
const services = ref([
  {
    id: '1',
    name: '修头部 小型犬',
    category: '美容',
    price: 80.0,
    description: '小型犬头部修剪服务',
  },
  {
    id: '2',
    name: '洗澡 小型犬',
    category: '洗澡',
    price: 60.0,
    description: '小型犬洗澡服务',
  },
  {
    id: '3',
    name: '修头部 大型犬',
    category: '美容',
    price: 120.0,
    description: '大型犬头部修剪服务',
  },
  {
    id: '4',
    name: '洗澡 大型犬',
    category: '洗澡',
    price: 100.0,
    description: '大型犬洗澡服务',
  },
  {
    id: '5',
    name: '修头部 猫',
    category: '美容',
    price: 100.0,
    description: '猫咪头部修剪服务',
  },
  {
    id: '6',
    name: '洗澡 猫',
    category: '洗澡',
    price: 80.0,
    description: '猫咪洗澡服务',
  },
  {
    id: '7',
    name: '指甲修剪',
    category: '护理',
    price: 30.0,
    description: '宠物指甲修剪服务',
  },
  {
    id: '8',
    name: '耳朵清洁',
    category: '护理',
    price: 25.0,
    description: '宠物耳朵清洁服务',
  },
  {
    id: '9',
    name: '造型设计',
    category: '造型',
    price: 150.0,
    description: '宠物造型设计服务',
  },
  {
    id: '10',
    name: '全身护理',
    category: '护理',
    price: 200.0,
    description: '宠物全身护理服务',
  },
]);

// 表格列定义
const columns = [
  { title: '名称', dataIndex: 'name', key: 'name', width: 200 },
  { title: '类别', dataIndex: 'category', key: 'category', width: 100 },
  { title: '价格', dataIndex: 'price', key: 'price', width: 100 },
  { title: '描述', dataIndex: 'description', key: 'description', width: 200 },
  { title: '操作', key: 'action', width: 80 },
];

// 计算属性
const filteredServices = computed(() => {
  let result = services.value;

  // 按类别筛选
  if (selectedCategory.value) {
    result = result.filter(
      (service) => service.category === selectedCategory.value,
    );
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    result = result.filter(
      (service) =>
        service.name.includes(searchKeyword.value) ||
        service.description.includes(searchKeyword.value),
    );
  }

  return result;
});

const totalAmount = computed(() => {
  return selectedServices.value.reduce((sum, service) => {
    return sum + service.price * service.quantity;
  }, 0);
});

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedServices.value.map((s) => s.id),
  onChange: (selectedRowKeys: string[], selectedRows: any[]) => {
    // 处理多选 - 这里可以添加批量选择逻辑
    console.log('选中的行:', selectedRowKeys, selectedRows);
  },
}));

// 方法
const searchServices = () => {
  // 搜索功能已通过计算属性实现
};

const filterServices = () => {
  // 筛选功能已通过计算属性实现
};

const selectService = (service: any) => {
  // 检查是否已经选择
  const existingIndex = selectedServices.value.findIndex(
    (s) => s.id === service.id,
  );
  if (existingIndex !== -1) {
    message.warning('该服务项目已选择');
    return;
  }

  // 添加到已选择列表
  selectedServices.value.push({
    ...service,
    quantity: 1,
  });

  message.success('服务项目已选择');
};

const removeService = (service: any) => {
  const index = selectedServices.value.findIndex((s) => s.id === service.id);
  if (index !== -1) {
    selectedServices.value.splice(index, 1);
    message.success('服务项目已移除');
  }
};

const clearAllSelected = () => {
  selectedServices.value = [];
  message.success('已清空所有选择的服务项目');
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const handleOk = () => {
  if (selectedServices.value.length === 0) {
    message.warning('请至少选择一个服务项目');
    return;
  }

  // 发送选中的服务项目
  emit('success', selectedServices.value);
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  searchKeyword.value = '';
  selectedCategory.value = '';
  selectedServices.value = [];
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      resetForm();
    }
  },
);
</script>

<style scoped>
.service-modal {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.search-section {
  flex-shrink: 0;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.services-list {
  flex: 1;
  margin-bottom: 16px;
  overflow-y: auto;
}

.selected-services {
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  max-height: 300px;
  padding: 16px 24px;
  margin: 0 -24px;
  overflow: hidden;
  background: #fafafa;
  border-top: 1px solid #e8e8e8;
}

.selected-header {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.selected-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.selected-list {
  flex: 1;
  max-height: 180px;
  margin-bottom: 12px;
  overflow-y: auto;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 8px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.service-info {
  flex: 1;
}

.service-name {
  margin-right: 8px;
  font-weight: bold;
}

.service-category {
  padding: 2px 6px;
  font-size: 12px;
  color: #666;
  background: #e6f7ff;
  border-radius: 2px;
}

.service-price {
  display: flex;
  align-items: center;
  margin-right: 16px;
}

.price {
  font-weight: bold;
  color: #1890ff;
}

.total-section {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: flex-end;
  padding: 12px 16px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
}

.total-label {
  margin-right: 8px;
  font-size: 16px;
  font-weight: bold;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #52c41a;
}

.modal-actions {
  display: flex;
  flex-shrink: 0;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 8px;
}

:deep(.ant-table-thead > tr > th) {
  padding: 8px;
  background: #fafafa;
}
</style>
